<?php
declare (strict_types=1);

namespace app\common\model;

class Product extends Base
{
    protected function type(): object
    {
        return $this->hasOne(ProductType::class, 'id', 'type_id')
            ->field('id,title');
    }

    protected function cate1(): object
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')
            ->field('id,title');
    }

    protected function cate2(): object
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')
            ->field('id,title');
    }

    protected function productSpec(): object
    {
        return $this->hasMany(ProductSpec::class, 'pid', 'id')
            ->field('id,pid,icon,merge_id,merge_title,price,vip_price,stock');
    }

    protected function getSpecDataAttr($value, $data): array
    {
        return $data['spec'] ? json_decode($data['spec'], true) : [];
    }

    public static function _save($param, $options): array
    {
        parent::startTrans();
        try {
            if (!empty($param['images'])) {
                $param['icon'] = explode(',', $param['images'])[0];
            }
            if (!empty($param['spec_open']) && $param['spec_open'] == 1) {
                $param['spec'] = '';
            }
            if (!empty($param['id'])) {
                $product = parent::update($param, ['id' => $param['id']]);
                ProductSpec::destroy(['pid' => $param['id']], true);
            } else {
                $product = parent::create($param);
            }
            if (!empty($param['spec_open']) && $param['spec_open'] == 2) {
                if (empty($param['spec']) || empty($param['specData'])) {
                    throw new \Exception('请设置规格');
                }
                $stock = 0;
                foreach ($param['specData'] as &$value) {
                    $value['pid'] = $product->id;
                    unset($value['title']);
                    foreach ($options['tape'] as &$tape) {
                        if (empty($tape['type'])) {
                            $tape['val'][] = $value[$tape['field']];
                        } else if ($tape['type'] == 'stock') {
                            $stock += intval($value[$tape['field']]);
                        }
                    }
                }
                (new ProductSpec())->insertAll($param['specData']);
                $product->spec = json_encode($param['spec']);
                $product->stock = $stock;
                foreach ($options['tape'] as $item) {
                    if (!empty($item['val'])) {
                        $product[$item['field']] = min($item['val']);
                    }
                }
                $product->save();
            }
            parent::commit();

            return ['code' => 1, 'msg' => '保存成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _delete($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where(['id' => $param['id']])->find();
            if (empty($info)) {
                throw new \Exception('该商品不存在');
            }
            ProductCart::destroy(['pid' => $info->id], true);
            parent::destroy(['id' => $info->id]);
            if ($admin) {
                Logs::adds("删除商品【{$info->id}】【{$info->title}】", $admin->id, $admin->admin_name);
            }
            parent::commit();

            return ['code' => 1, 'msg' => '删除成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}